(ns leiningen.new.gen.core
  (:import (java.io File))
  (:require [clojure.java.io :as io]
            [clojure.string :as str]))

(def gen-files (atom []))
(def dest-dir "src/leiningen/new/compojure_misty")

(defn- split-name [n]
  (let [idx (.lastIndexOf n ".")]
    [(subs n 0 idx) (subs n (inc idx))]))

(defmulti gen-file (fn [^File f & [prefix postfix]]
                     (if (.isFile f) :file :dir)))

(defmethod gen-file :file [^File f & [prefix postfix]]
  (println "gen " f)
  (swap! gen-files conj f)
  (let [[fname ext] (split-name (.getName f))
        fname (if prefix (str prefix "_" fname) fname)
        fname (if postfix (str fname "_" postfix) fname)
        dest (io/file dest-dir (str fname "." ext))
        content (slurp f)
        content-1 (-> content
                      (str/replace "projectname" "{{name}}")
                      (str/replace "projectpath" "{{sanitized}}"))]
    (spit dest content-1)))

(defmethod gen-file :dir [^File f & [prefix postfix]]
  (println "=== gen " f "===")
  (let [fseq (file-seq f)]
    (doseq [e fseq]
      (if (.isFile e)
        (gen-file e prefix postfix)
        (swap! gen-files conj e)))))

(defn do-gen []
  (let [temp-dir (io/file "template-misty")

        project-file (io/file temp-dir "project.clj")
        gitignore (io/file temp-dir ".gitignore")
        readme (io/file temp-dir "README.md")
        src (io/file temp-dir "src")
        resources (io/file temp-dir "resources")
        test (io/file temp-dir "test")]
    (gen-file project-file)
    (gen-file gitignore)
    (gen-file readme)
    (gen-file resources)
    (gen-file src)
    (gen-file test nil "test")
    )
  (println "========== gen files ==========")
  (doseq [f @gen-files]
    (println f)))